package com.hjj.springboot.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hjj.springboot.entity.*;
import com.hjj.springboot.service.IOrderDetailService;
import com.hjj.springboot.service.IOrderService;
import com.hjj.springboot.util.DateUtil;
import com.hjj.springboot.util.JwtUtils;
import com.hjj.springboot.util.StringUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.List;

@RestController
@RequestMapping("/my/order")
public class OrderController {

    @Autowired
    private IOrderService orderService;

    @Autowired
    private IOrderDetailService orderDetailService;


    /**
     * 创建订单，返回订单号
     */
    @RequestMapping("/create")
    @Transactional
    public R create(@RequestBody Order order, @RequestHeader(value="token") String token){
        System.out.println("token:"+token);
        // 通过token获取openid
        Claims claims = JwtUtils.validateJWT(token).getClaims();
        if(claims!=null){
            System.out.println("openid="+claims.getId());
            order.setUserId(claims.getId());
        }
        order.setOrderNo("SXCS"+ DateUtil.getCurrentDateStr());
        order.setCreateDate(new Date());

        OrderDetail[] goods = order.getGoods();

        // 添加订单到数据库
        orderService.save(order);
        // 添加订单详情到数据库
        for (OrderDetail orderDetail : goods) {
            orderDetail.setMId(order.getId());
            orderDetailService.save(orderDetail);
        }
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("orderNo",order.getOrderNo());
        return R.ok(resultMap);
    }

    //支付
    @RequestMapping("/pay")
    public R pay(@RequestBody String orderNo) {
        System.out.println("orderNo:"+orderNo);
        Order order=orderService.getOne(new QueryWrapper<Order>().eq("orderNo", orderNo));
        if(order!=null && order.getStatus()==1){
            order.setPayDate(new Date());
            order.setStatus(2); //设置已支付状态
            orderService.saveOrUpdate(order);
        }
        return R.ok();

    }


    /**
     * 订单查询  type 值 0 全部订单  1 待付款   2  待发货  3 待接单 4 配送中 5 待收货 6 待评价 7 已完成 8 退款/退货
     */
    @RequestMapping("/list")
    public R list(Integer type,Integer page,Integer pageSize){
        System.out.println("type="+type);
        List<Order> orderList;
        Map<String,Object> resultMap=new HashMap<>();

        Page<Order> pageOrder=new Page<>(page,pageSize);

        if(type==0){  // 全部订单查询
//             orderList=orderService.list(new QueryWrapper<Order>().orderByDesc("id"));
            Page<Order> orderResult = orderService.page(pageOrder, new QueryWrapper<Order>().orderByDesc("id"));
            System.out.println("总记录数："+orderResult.getTotal());
            System.out.println("总页数："+orderResult.getPages());
            System.out.println("当前页数据："+orderResult.getRecords());
            orderList=orderResult.getRecords();
            for(Order order:orderList){
                OrderDetail[] goods= orderDetailService.list(new QueryWrapper<OrderDetail>().eq("mId",order.getId())).toArray(new OrderDetail[0]);
                order.setGoods(goods);
            }
            resultMap.put("total",orderResult.getTotal());
            resultMap.put("totalPage",orderResult.getPages());
        }else{
            // orderList = orderService.list(new QueryWrapper<Order>().eq("status", type).orderByDesc("id"));
            Page<Order> orderResult = orderService.page(pageOrder, new QueryWrapper<Order>().eq("status", type).orderByDesc("id"));
            System.out.println("总记录数："+orderResult.getTotal());
            System.out.println("总页数："+orderResult.getPages());
            System.out.println("当前页数据："+orderResult.getRecords());
            orderList=orderResult.getRecords();
            for(Order order:orderList){
                OrderDetail[] goods= orderDetailService.list(new QueryWrapper<OrderDetail>().eq("mId",order.getId())).toArray(new OrderDetail[0]);
                order.setGoods(goods);
            }
            resultMap.put("total",orderResult.getTotal());
            resultMap.put("totalPage",orderResult.getPages());
        }
        resultMap.put("orderList",orderList);
        return R.ok(resultMap);
    }

    @RequestMapping("/detail")
    public R detail(Integer id){
        OrderDetail[] goods=orderDetailService.list(new QueryWrapper<OrderDetail>().eq("mId",id)).toArray(new OrderDetail[0]);
        Order order=orderService.getById(id);
        order.setGoods(goods);
        Map<String,Object> map=new HashMap<>();
        map.put("message",order);
        return R.ok(map);
    }


    @RequestMapping("/getNum")
    public R getNum(String openid){
        List<Order> orderList=orderService.list(new QueryWrapper<Order>().eq("userId", openid));
        orderList.removeIf(order -> order.getStatus()==1);
        System.out.println(orderList);
        int totalPayNum=orderList.size();
        BigDecimal totalPrice = orderList.stream().map(Order::getTotalPrice).reduce(BigDecimal.ZERO, BigDecimal::add);
        System.out.println(totalPrice);
        Map<String,Object> map=new HashMap<>();
        map.put("totalPayNum",totalPayNum);
        map.put("totalPrice",totalPrice);
        return R.ok(map);
    }

    // 取消订单
    @RequestMapping("/cancel")
    public R cancel(Integer id){
        List<OrderDetail> list=orderDetailService.list(new QueryWrapper<OrderDetail>().eq("mId",id));
        orderService.removeById(id);
        for(OrderDetail orderDetail:list){
            orderDetailService.removeById(orderDetail.getId());
        }
        return R.ok();
    }

    // 确认收货
    @RequestMapping("/sure")
    public R sure(@RequestParam Integer id , @RequestParam String query){
        System.out.println(id);
        System.out.println(query);
        Order order=orderService.getById(id);
        if(order!=null && order.getStatus()==5 && StringUtil.isNotEmpty(query)){
            order.setStatus(6); //设置待评价状态
            orderService.saveOrUpdate(order);
        }
        return R.ok();
    }

    @RequestMapping("/comment")
    public R comment(Integer id){
        Order order=orderService.getById(id);
        if(order!=null && order.getStatus()==6){
            order.setStatus(7);
            orderService.saveOrUpdate(order);
        }
        return R.ok();
    }

}


